package org.jeecg.modules.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanMap;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.BeanPlusUtil;
import org.jeecg.modules.business.entity.BussContractReviewDes;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.mapper.FlowMyBusinessMapper;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.storage.entity.BussStorageNotice;
import org.jeecg.modules.storage.entity.BussStorageNoticeCarinfo;
import org.jeecg.modules.storage.entity.BussStorageNoticeMaterial;
import org.jeecg.modules.storage.service.IBussStorageNoticeCarinfoService;
import org.jeecg.modules.storage.service.IBussStorageNoticeMaterialService;
import org.jeecg.modules.storage.service.IBussStorageNoticeService;
import org.jeecg.modules.storage.vo.BussStorageNoticeCarinfoVo;
import org.jeecg.modules.storage.vo.BussStorageNoticeMaterialVo;
import org.jeecg.modules.storage.vo.BussStorageNoticePage;
import org.jeecg.modules.storage.vo.StoragePage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 入库通知单
 * @Author: jeecg-boot
 * @Date:   2024-06-18
 * @Version: V1.0
 */
@Api(tags="入库通知单")
@RestController
@RequestMapping("/business/bussStorageNotice")
@Slf4j
public class BussStorageNoticeController {
	@Autowired
	private IBussStorageNoticeService bussStorageNoticeService;
	@Autowired
	private IBussStorageNoticeCarinfoService bussStorageNoticeCarinfoService;
	@Autowired
	private IBussStorageNoticeMaterialService bussStorageNoticeMaterialService;
	@Autowired
	private IFlowDefinitionService flowDefinitionService;

	@Autowired
	private FlowMyBusinessMapper flowMyBusinessMapper;
	/**
	 * 分页列表查询
	 *
	 * @param bussStorageNotice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "入库通知单-分页列表查询")
	@ApiOperation(value="入库通知单-分页列表查询", notes="入库通知单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BussStorageNoticePage>> queryPageList(BussStorageNoticePage bussStorageNotice,
														  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														  HttpServletRequest req) {
		QueryWrapper<BussStorageNoticePage> queryWrapper = QueryGenerator.initQueryWrapper(bussStorageNotice, req.getParameterMap());
		Page<BussStorageNoticePage> page = new Page<BussStorageNoticePage>(pageNo, pageSize);
		Map<String, String[]> ParameterMap = new HashMap<String, String[]>(req.getParameterMap());
		String[] column = new String[]{""};
		if(ParameterMap!=null&&  ParameterMap.containsKey("column")) {
			column[0] = ParameterMap.get("column")[0];
			column[0] = "t."+ column[0];
			ParameterMap.replace("column", column);
			log.info("修改的排序规则>>列:" + ParameterMap.get("column")[0]);
		}
		IPage<BussStorageNoticePage> pageList = bussStorageNoticeService.pagelist(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param bussStorageNoticePage
	 * @return
	 */
	@AutoLog(value = "入库通知单-添加")
	@ApiOperation(value="入库通知单-添加", notes="入库通知单-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_storage_notice:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BussStorageNoticePage bussStorageNoticePage) {
		BussStorageNotice bussStorageNotice = new BussStorageNotice();
		BeanUtils.copyProperties(bussStorageNoticePage, bussStorageNotice);
		bussStorageNoticeService.saveMain(bussStorageNotice, bussStorageNoticePage.getBussStorageNoticeCarinfoList(),bussStorageNoticePage.getBussStorageNoticeMaterialList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param bussStorageNoticePage
	 * @return
	 */
	@AutoLog(value = "入库通知单-编辑")
	@ApiOperation(value="入库通知单-编辑", notes="入库通知单-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_storage_notice:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BussStorageNoticePage bussStorageNoticePage) {
		BussStorageNotice bussStorageNotice = new BussStorageNotice();
		BeanUtils.copyProperties(bussStorageNoticePage, bussStorageNotice);
		BussStorageNotice bussStorageNoticeEntity = bussStorageNoticeService.getById(bussStorageNotice.getId());
		if(bussStorageNoticeEntity==null) {
			return Result.error("未找到对应数据");
		}
		bussStorageNoticeService.updateMain(bussStorageNotice, bussStorageNoticePage.getBussStorageNoticeCarinfoList(),bussStorageNoticePage.getBussStorageNoticeMaterialList());
		return Result.OK("编辑成功!");
	}

	/**
	 * 撤回
	 * @param id
	 * @return
	 */
	@ApiOperation(value="撤回", notes="撤回")
	@GetMapping("/retract")
	public Result retract(@RequestParam String id){
		this.bussStorageNoticeService.retract(id);
		return Result.ok();
	}

	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "入库通知单-通过id删除")
	@ApiOperation(value="入库通知单-通过id删除", notes="入库通知单-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_storage_notice:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		bussStorageNoticeService.deleteMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "入库通知单-批量删除")
	@ApiOperation(value="入库通知单-批量删除", notes="入库通知单-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:buss_storage_notice:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bussStorageNoticeService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "入库通知单-通过id查询")
	@ApiOperation(value="入库通知单-通过id查询", notes="入库通知单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BussStorageNotice> queryById(@RequestParam(name="id",required=true) String id) {
		BussStorageNotice bussStorageNotice = bussStorageNoticeService.getById(id);
		if(bussStorageNotice==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(bussStorageNotice);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "入库通知单-车辆信息通过主表ID查询")
	@ApiOperation(value="入库通知单-车辆信息主表ID查询", notes="入库通知单-车辆信息-通主表ID查询")
	@GetMapping(value = "/queryBussStorageNoticeCarinfoByMainId")
	public Result<List<BussStorageNoticeCarinfoVo>> queryBussStorageNoticeCarinfoListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussStorageNoticeCarinfoVo> bussStorageNoticeCarinfoList = bussStorageNoticeCarinfoService.selectByMainId(id);
		return Result.OK(bussStorageNoticeCarinfoList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "入库通知单原料单通过主表ID查询")
	@ApiOperation(value="入库通知单原料单主表ID查询", notes="入库通知单原料单-通主表ID查询")
	@GetMapping(value = "/queryBussStorageNoticeMaterialByMainId")
	public Result<List<BussStorageNoticeMaterialVo>> queryBussStorageNoticeMaterialListByMainId(@RequestParam(name="id",required=true) String id) {
		List<BussStorageNoticeMaterialVo> bussStorageNoticeMaterialList = bussStorageNoticeMaterialService.selectByMainId(id);
		return Result.OK(bussStorageNoticeMaterialList);
	}

	/**
	 * 检查入库单数量
	 * @param vo
	 * @return
	 */
	@PostMapping("/checkProcMaterialNum")
	public Result checkProcMaterialNum(@RequestBody BussStorageNoticeMaterialVo vo){
		this.bussStorageNoticeService.checkProcMaterialNum(vo);
		return Result.ok();
	}

    /**
    * 导出excel
    *
    * @param request
    * @param bussStorageNotice
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_storage_notice:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BussStorageNoticePage bussStorageNotice,
								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<BussStorageNoticePage> queryWrapper = QueryGenerator.initQueryWrapper(bussStorageNotice, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		Page<BussStorageNoticePage> page = new Page<BussStorageNoticePage>(pageNo, pageSize);
      //配置选中数据查询条件
//      String selections = request.getParameter("selections");
//      if(oConvertUtils.isNotEmpty(selections)) {
//         List<String> selectionList = Arrays.asList(selections.split(","));
//         queryWrapper.in("id",selectionList);
//      }
      //Step.2 获取导出数据
		//pagelist
		IPage<BussStorageNoticePage> bussStorageNoticePageIPage = bussStorageNoticeService.exportList(page, queryWrapper);
		List<BussStorageNoticePage> records = bussStorageNoticePageIPage.getRecords();
//      List<BussStorageNotice> bussStorageNoticeList = bussStorageNoticeService.list(queryWrapper);

      // Step.3 组装pageList
//      List<BussStorageNoticePage> pageList = new ArrayList<BussStorageNoticePage>();
//      for (BussStorageNoticePage main : records) {
//          BussStorageNoticePage vo = new BussStorageNoticePage();
//          BeanUtils.copyProperties(main, vo);
////          List<BussStorageNoticeCarinfoVo> bussStorageNoticeCarinfoList = bussStorageNoticeCarinfoService.selectByMainId(main.getId());
////          vo.setBussStorageNoticeCarinfoList(BeanPlusUtil.toBeanList(bussStorageNoticeCarinfoList,BussStorageNoticeCarinfo.class) );
////		  List<BussStorageNoticeMaterialVo> bussStorageNoticeMaterialVos = bussStorageNoticeMaterialService.selectByMainId(main.getId());
////		  vo.setBussStorageNoticeMaterialVoList(bussStorageNoticeMaterialVos);
//          pageList.add(vo);
//      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "入库单列表");
      mv.addObject(NormalExcelConstants.CLASS, BussStorageNoticePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库单数据", "导出人:"+sysUser.getRealname(), "入库通知单"));
      mv.addObject(NormalExcelConstants.DATA_LIST, records);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("org.jeecg.modules.demo:buss_storage_notice:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<BussStorageNoticePage> list = ExcelImportUtil.importExcel(file.getInputStream(), BussStorageNoticePage.class, params);
              for (BussStorageNoticePage page : list) {
                  BussStorageNotice po = new BussStorageNotice();
                  BeanUtils.copyProperties(page, po);
                  bussStorageNoticeService.saveMain(po, page.getBussStorageNoticeCarinfoList(),page.getBussStorageNoticeMaterialList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }
	//@AutoLog(value = "合同评审说明-反审核")
	@ApiOperation(value="合同评审说明-反审核", notes="合同评审说明-反审核")
	@GetMapping(value = "/reverseCheck")
	public Result<BussContractReviewDes> reverseCheck(@RequestParam(name="id",required=true) String id) {
		BussStorageNotice bussStorageNotice = bussStorageNoticeService.getById(id);
		if(bussStorageNotice==null) {
			return Result.error("未找到对应数据");
		}
		bussStorageNotice.setDisuse(1);
		bussStorageNoticeService.updateById(bussStorageNotice);
		BussStorageNotice copyDes = new BussStorageNotice();
		BeanUtils.copyProperties(bussStorageNotice, copyDes,"createTime","updateTime","updateBy","createBy","id","disuse");
		bussStorageNoticeService.save(copyDes);
		String dataId = copyDes.getId();
		//todo 子表相关信息 添加
		List<BussStorageNoticeMaterialVo> bussStorageNoticeMaterialVos = bussStorageNoticeMaterialService.selectByMainId(bussStorageNotice.getId());
		List<BussStorageNoticeMaterial> bussStorageNoticeMaterials = BeanPlusUtil.toBeanList(bussStorageNoticeMaterialVos, BussStorageNoticeMaterial.class, "createTime", "updateTime", "updateBy", "createBy", "noticeId","id");
		bussStorageNoticeMaterials.stream().forEach(item->item.setNoticeId(dataId));
		bussStorageNoticeMaterialService.saveBatch(bussStorageNoticeMaterials);
		List<BussStorageNoticeCarinfo> bussStorageNoticeCarinfos = BeanPlusUtil.toBeanList(bussStorageNoticeCarinfoService.selectByMainId(bussStorageNotice.getId()), BussStorageNoticeCarinfo.class, "createTime", "updateTime", "updateBy", "createBy", "noticeId","id");
		bussStorageNoticeCarinfos.stream().forEach(item-> item.setNoticeId(dataId));
		bussStorageNoticeCarinfoService.saveBatch(bussStorageNoticeCarinfos);

		BeanMap variables = new BeanMap(copyDes);
		FlowMyBusiness flowMyBusiness = flowMyBusinessMapper.selectOne(new LambdaQueryWrapper<FlowMyBusiness>().eq(FlowMyBusiness::getDataId, id).last(" limit 1"));
		if (Objects.isNull(flowMyBusiness)) {
			return Result.error("该表单尚未发起审批,不可以发起反审核操作");
		}
		String actStatus = flowMyBusiness.getActStatus();
		if (!"审批通过".equals(actStatus)){
			return Result.error("只有审批通过的表单可以发起反审核操作");
		}
		// 转换为 Map<String, Object>
		Map<String, Object> map = new HashMap<>();
		for (Object key : variables.keySet()) {
			map.put((String) key, variables.get(key));
		}
		map.put("dataId",dataId);
		return flowDefinitionService.startProcessInstanceByDataId(dataId, "bussStorageNoticeServiceImpl", map);
	}

	@ApiOperation(value="入库单-查询没有进行质检的", notes="入库单-查询没有进行质检的")
	@GetMapping(value = "/storageList")
	public Result<IPage<StoragePage>> queryStorageList(StoragePage bussStoragePage,
													   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													   HttpServletRequest req) {
		QueryWrapper<StoragePage> queryWrapper = QueryGenerator.initQueryWrapper(bussStoragePage, req.getParameterMap());
		Page<StoragePage> page = new Page<StoragePage>(pageNo, pageSize);
		IPage<StoragePage> pageList = bussStorageNoticeService.queryList(page, queryWrapper);
		return Result.OK(pageList);
	}
}
